package com.imufe.chemicalenterprisedangerwarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imufe.chemicalenterprisedangerwarning.entity.po.CheckUnitPO;
import com.imufe.chemicalenterprisedangerwarning.entity.po.ChemicalPO;
import com.imufe.chemicalenterprisedangerwarning.entity.po.UnitItemPO;
import com.imufe.chemicalenterprisedangerwarning.entity.query.CheckUnitQuery;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.CheckUnitDetailedVO;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.UnitItemDetailedVO;
import com.imufe.chemicalenterprisedangerwarning.exception.ValidationException;
import com.imufe.chemicalenterprisedangerwarning.mapper.CheckItemMapper;
import com.imufe.chemicalenterprisedangerwarning.mapper.CheckUnitMapper;
import com.imufe.chemicalenterprisedangerwarning.service.CheckUnitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imufe.chemicalenterprisedangerwarning.service.UnitItemService;
import com.imufe.chemicalenterprisedangerwarning.util.BeanUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 检查模块表 服务实现类
 * </p>
 *
 * @author BaiBan
 * @since 2022-10-06
 */
@Log4j2
@Service
public class CheckUnitServiceImpl extends ServiceImpl<CheckUnitMapper, CheckUnitPO> implements CheckUnitService {

    @Autowired
    CheckUnitMapper mapper;

    @Autowired
    UnitItemService  unitItemService;

    @Override
    public CheckUnitDetailedVO detailed(Long id) {
        CheckUnitPO po = mapper.selectById(id);
        CheckUnitDetailedVO detailedVO = BeanUtils.copyPOJO(po, CheckUnitDetailedVO.class);

        // 获取这个模块的所有条目
        QueryWrapper<UnitItemPO> qw = new QueryWrapper<>();
        List<UnitItemPO> list = unitItemService.list(qw);
        List<UnitItemDetailedVO> items = list.stream().map(unitItemPO -> {
            try {
                return unitItemService.detailed(unitItemPO.getId());
            } catch (ValidationException e) {
                throw new RuntimeException(e);
            }
        }).toList();

        detailedVO.setItems(items);
        return detailedVO;
    }

    @Override
    public List<CheckUnitDetailedVO> list(Long enterpriseId) {
        QueryWrapper<CheckUnitPO> qw = new QueryWrapper<>();
        qw.eq("enterprise_id", enterpriseId);
        List<CheckUnitPO> pos = mapper.selectList(qw);
        return pos.stream().map(po -> this.detailed(po.getId())).toList();
    }

    @Override
    public CheckUnitDetailedVO create(CheckUnitQuery query) throws ValidationException {
        // 权值和加新权值超过了100
        if (toFraction(query.getEnterpriseId(), null) + query.getWeight() > 100)
            throw new ValidationException("权重超过上限");

        CheckUnitPO po = BeanUtils.copyPOJO(query, CheckUnitPO.class);
        log.info(po);
        mapper.insert(po);
        return this.detailed(po.getId());
    }

    @Override
    public CheckUnitDetailedVO update(CheckUnitQuery query) throws ValidationException {
        // 修改权值 并且 权值和加新权值超过了100
        if (query.getWeight() != null && toFraction(query.getEnterpriseId(), query.getId()) + query.getWeight() > 100)
            throw new ValidationException("权重超过上限");

        CheckUnitPO po = BeanUtils.copyPOJO(query, CheckUnitPO.class);
        log.info(po);
        mapper.updateById(po);
        return this.detailed(po.getId());
    }

    /**
     * 根据企业获取分数 排除一个模块
     * @param enterpriseId 企业编号
     * @param checkUnitId 被排除的模块
     * @return 所属该企业剩余模块权限和
     */
    private Long toFraction(Long enterpriseId, Long checkUnitId) {

        QueryWrapper<CheckUnitPO> qw = new QueryWrapper<>();
        qw.eq("is_discard", 0).eq("enterprise_id", enterpriseId);
        if (checkUnitId != null)
            qw.ne("id", checkUnitId);
        qw.select("IFNULL(SUM(weight), 0)");
        return Long.parseLong(String.valueOf(mapper.selectObjs(qw).get(0)));
    }
}